package com.slz3.business.module.drawManagement.draIntegralLottery.service;

import com.slz3.business.frame.enums.ValidFlag;
import com.slz3.business.frame.enums.YNFlag;
import com.slz3.business.frame.module.Repositorys;
import com.slz3.business.frame.module.Services;
import com.slz3.business.frame.redis.Jedis;
import com.slz3.business.frame.redis.RK;
import com.slz3.business.frame.steward.PageableSteward;
import com.slz3.business.frame.steward.Steward;
import com.slz3.business.frame.task.DynamicScheduleTaskSecond;
import com.slz3.business.frame.util.VE;
import com.slz3.business.module.drawManagement.draIntegralLottery.domain.DraIntegralLottery;
import com.slz3.business.module.drawManagement.draIntegralLottery.domain.DraIntegralLotteryFactory;
import com.slz3.business.module.drawManagement.draIntegralLottery.steward.DraIntegralLotterySpecification;
import com.slz3.business.module.goodsManagement.gooBrand.domain.GooBrand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DraIntegralLotteryServiceImpl implements DraIntegralLotteryService {
    @Override
    public DraIntegralLottery save(DraIntegralLottery draIntegralLottery) {
        return Repositorys.draIntegralLottery.save(DraIntegralLotteryFactory.initBaseFields(draIntegralLottery));
    }

    @Override
    public Page<DraIntegralLottery> page(MultiValueMap<String, String> params) {
        Page<DraIntegralLottery> draIntegralLotteryPage = Repositorys.draIntegralLottery.findAll(
                DraIntegralLotterySpecification.findJoin(params), PageableSteward.extract(params)
        );
        // join
        Map<UUID, GooBrand> joinGooBrand = Repositorys.gooBrand.findAllById(
                draIntegralLotteryPage.getContent().stream().map(DraIntegralLottery::getSerGoodsDrawBrand).collect(Collectors.toList())
        ).stream().collect(Collectors.toMap(GooBrand::getUuid, Function.identity()));
        // merge
        draIntegralLotteryPage.getContent().stream().forEach(item -> item.setGooBrand(joinGooBrand.get(item.getSerGoodsDrawBrand())));
        //
        return draIntegralLotteryPage;
    }


    @Override
    public DraIntegralLottery modify(DraIntegralLottery draIntegralLotteryNew) {
        return Repositorys.draIntegralLottery.saveAndFlush(DraIntegralLotteryFactory.initBaseFields(draIntegralLotteryNew));
    }

    @Override
    public Optional<DraIntegralLottery> single(UUID uuid) {
        return Repositorys.draIntegralLottery.findById(uuid);
    }

    @Override
    public List<DraIntegralLottery> findAllByUuids(Iterable<UUID> uuids) {
        return Repositorys.draIntegralLottery.findAllById(uuids);
    }

    @Override
    public List<DraIntegralLottery> delete(List<DraIntegralLottery> draIntegralLotteryList) {
        draIntegralLotteryList.stream().forEach(item -> {
            item.setValidFlag(ValidFlag.DEL);
            DraIntegralLotteryFactory.initBaseFields(item);
        });
        return Services.draIntegralLotteryTransactional.batchModify(draIntegralLotteryList);
    }

    // TODO 回滚
    @Override
    public List<DraIntegralLottery> lottery(List<DraIntegralLottery> draIntegralLotteryList) {
        draIntegralLotteryList.stream().forEach(item -> {
            item.setSerAlreadyLotteryEnum(YNFlag.YES);
            DraIntegralLotteryFactory.initBaseFields(item);
        });
        List<DraIntegralLottery> list = draIntegralLotteryList;

        /**
         * 逻辑概要：
         * 1 当前活动下谁中奖了
         * 2 会员参加的活动中的中奖活动
         */
        if (VE.isNotEmpty(list)) {
            list.forEach(item -> {
                /**
                 * 当前活动下谁中奖了
                 */
                // redis key
                String memberuuidUuidKey = RK.SERVICE__DRAW__WINALERT__MEMBERUUID__$UUID;//中奖人-中奖活动
                String draItemKey = RK.BUSSINESS__DRAW__DRA_INTEGRAL_LOTTERY__DRAW_ITEM__PARTAKE__$INCREMENT_ID__DATA_MAP
                        .replace("${IncrementId}", item.getIncrementId().toString());
                // 本活动下所有的参与人信息
                List<Map<String, Object>> draItemFMList = Jedis.db0.getListStartEnd(
                        draItemKey, 0, Jedis.db0.getListLen(draItemKey)
                );
                //
                String memberIncrementId = null;
                String memberUuid = null;
                Map<String, Object> memberFM = null;
                //
                if (VE.isNotEmpty(draItemFMList)) {
                    // 开奖活动-中奖人
                    for (int i = 0; i < draItemFMList.size(); i++) {
                        Map<String, Object> draItemFM = draItemFMList.get(i);
                        String number = Optional.ofNullable(draItemFM.get("number")).orElse("-").toString();
                        if (number.equals(item.getSerGoodsDrawNumber())) {
                            /** 中奖会员 **/
                            memberIncrementId = Optional.ofNullable(draItemFM.get("userId")).orElse("-").toString();
                            memberUuid = Jedis.db0.get(RK.ID_MAP_UUID__API__$INCREMENT_ID$.replace("${incrementId}", memberIncrementId));
                            memberFM = Jedis.db0.getMap(RK.MEM_MEMBER__INFO__$UUID$.replace("${uuid}", memberUuid));
                            memberuuidUuidKey.replace("${uuid}", memberIncrementId);
                            draItemFM.put("wining", "Yes");
                            draItemFM.put("headImg", Optional.ofNullable(memberFM.get("picture")).orElse(""));
                            Jedis.db0.redisTemplate.opsForList().set(draItemKey, i, draItemFM);

                            List userList = new ArrayList<UUID>();
                            userList.add(UUID.fromString(memberUuid));
                            List allByUuids1 = Services.memMember.findAllByUuids(userList);
                            Map map = new HashMap();
                            map.put("MESSAGETYPE","SMS_151996100");
                            map.put("hdUuid",item.getUuid());
                            DynamicScheduleTaskSecond.sendMessage(item.getSerGoodsDrawName(),allByUuids1,map);
                            break;
                        }
                    }
                }
                /**
                 * 会员参加的活动中的中奖活动
                 */
                if (memberIncrementId != null) {
                    // 中奖人-中奖活动
                    // redis key
                    String draMemberKey = RK.BUSSINESS__DRAW__DRA_INTEGRAL_LOTTERY__MEM_MEMBER__PARTAKE__$INCREMENT_ID__DATA_MAP
                            .replace("${IncrementId}", memberIncrementId);
                    List<Map<String, Object>> draMemberFMList = Jedis.db0.getListStartEnd(
                            draMemberKey, 0, Jedis.db0.getListLen(draMemberKey)
                    );
                    if (VE.isNotEmpty(draMemberFMList)) {
                        for (int i = 0; i < draMemberFMList.size(); i++) {
                            Map<String, Object> draMemberFM = draMemberFMList.get(i);
                            String drawId = Optional.ofNullable(draMemberFM.get("drawId")).orElse("-").toString();
                            if (drawId.equals(item.getUuid().toString())) {
                                /** 中奖活动 **/
                                draMemberFM.put("wining", "Yes");
                                draMemberFM.put("headImg", Optional.ofNullable(memberFM.get("picture")).orElse(""));
                                Jedis.db0.redisTemplate.opsForList().set(draMemberKey, i, draMemberFM);
                                Jedis.db0.set(RK.DAW_WINNER_UNRECEIVE_REMIND__$UUID$.replace("${dawid}",item.getUuid().toString()).replace("${uuid}",memberUuid),0,RK.DAW_WINNER_UNRECEIVE_TIME);//失效时间五天
                                Jedis.db0.set(RK.DAW_WINNER_UNRECEIVE_REMIND__HASH.replace("${dawid}",item.getUuid().toString()).replace("${uuid}",memberUuid), Steward.obj2Map(item));//失效时间五天
//                                String kkey = memberuuidUuidKey.replace("${uuid}", memberUuid);
//                                Jedis.db0.redisTemplate.opsForList().rightPush()
//                                Jedis.db0.redisTemplate.opsForList().set(kkey, i, drawId);
                                break;
                            }
                        }
                    }
                    //活动管理的中奖用户ID，活动ID
                    //以用户的ID为key，活动ID为值进行存储
                    String user_winning_recod_key = RK.USER_BUSSINESS_INTEGRAL_DRAW_WINNING_RECORD.replace("${memberid}", memberIncrementId);
                    Jedis.db0.lpush(user_winning_recod_key, item.getIncrementId());
                }
            });
        }

        Services.draIntegralLotteryTransactional.batchModify(draIntegralLotteryList);

        return list;
    }

}
